package cn.demomaster.quickpermission;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import cn.demomaster.quickpermission.dialog.DialogWindowActivity;
import cn.demomaster.quickpermission.listener.IPermissionHandler;
import cn.demomaster.quickpermission.util.PermissionGroupUtil;

public class PermissionHandler implements IPermissionHandler {

    /**
     * 显示权限申请弹窗
     *
     * @param context
     * @param request
     */
    public void showPermissionDialog(Context context, PermissionRequest request) {
        String permission = request.getCurrentPermission();//.get(request.getIndex());
        String title = context.getString(R.string.permission_application);
        showAlert(context, title, PermissionGroupUtil.getPermissionDescription(permission), !handlePermissionDenial(context, request), (dialog, which) -> {
                    QuickPermission2.getInstance().requestPermissionImpl(request);
                }
                , (dialog, which) -> {
                    dialog.dismiss();
                    request.cancel();
                });
    }

    public void onStartPermissionActivity(Context context, PermissionRequest request) {
        String permissionName = request.getCurrentPermission();
        if (permissionName.equals(Manifest.permission.SYSTEM_ALERT_WINDOW)
                || permissionName.equals(Manifest.permission.BIND_ACCESSIBILITY_SERVICE)) {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(() -> {
                Intent intent = new Intent(context, DialogWindowActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("permission", permissionName);
                intent.putExtras(bundle);
                if (!(context instanceof Activity)) {
                    intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                }
                (context).startActivity(intent);
                // 参数1：SecondActivity进场动画，参数2：MainActivity出场动画
                if (context instanceof Activity) {
                    ((Activity) context).overridePendingTransition(0, 0);
                }
            });
        }
    }

    /**
     * 处理权限申请，可以重写来自定义申请逻辑
     *
     * @param context 上下文环境
     * @param request
     * @return
     */
    @Override
    public boolean handleRequestPermission(Context context, PermissionRequest request) {
        String permission = request.getCurrentPermission();
        System.out.println("处理权限：" + permission);
        //弹框提示用户手动打开 处理特殊权限
        switch (permission) {
            case Manifest.permission.INSTALL_PACKAGES:
            case Manifest.permission.REQUEST_INSTALL_PACKAGES:
            case Manifest.permission.SYSTEM_ALERT_WINDOW:
            case Manifest.permission.PACKAGE_USAGE_STATS:
            case Manifest.permission.WRITE_SETTINGS:
            case Manifest.permission.BIND_ACCESSIBILITY_SERVICE:
                showPermissionDialog(context, request);
                return true;
            case Manifest.permission.MANAGE_EXTERNAL_STORAGE:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    showPermissionDialog(context, request);
                    return true;
                }
                return false;
            default:
                ActivityCompat.requestPermissions(QuickPermission2.activityWeakReference.get(), new String[]{permission}, request.getRequestCode());
                return true;
        }
        //return false;
    }

    /**
     * 权限被拒绝，
     *
     * @param context
     * @param request
     * @return true 重新申请 false 忽略继续申请下一个
     */
    @Override
    public boolean handlePermissionDenial(Context context, PermissionRequest request) {
        //PermissionModel permissionModel
        String permission = request.getCurrentPermission();
        int rcode = ContextCompat.checkSelfPermission(context, permission);

        switch (permission) {
            case Manifest.permission.SYSTEM_ALERT_WINDOW:
                return false;
            case Manifest.permission.INSTALL_PACKAGES:
                return false;
        }
        System.out.println("权限被拒绝：" + permission + "  " + rcode);
        return false;//返回此权限是否必须，若是必要权限可以返回true，重复请求
    }

    static AlertDialog.Builder builder;
    static AlertDialog dialog;

    /**
     * alert 消息提示框显示
     *
     * @param context  上下文
     * @param title    标题
     * @param message  消息
     * @param listener 监听器
     */
    public static void showAlert(Context context, String title, String message, boolean cancelable, DialogInterface.OnClickListener listener, DialogInterface.OnClickListener dissmisslistener) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton("确定", listener);
        if (cancelable) {
            builder.setNegativeButton("取消", dissmisslistener);
        }
        builder.setCancelable(cancelable);
        //builder.setIcon(R.mipmap.quickdevelop_ic_launcher);
        dialog = builder.create();
        dialog.show();
    }

    /**
     * alert 消息提示框显示
     *
     * @param context  上下文
     * @param title    标题
     * @param message  消息
     * @param listener 监听器
     */
    public static void showAlertPermissionSetting(Context context, String title, String message, boolean cancelable, DialogInterface.OnClickListener listener, DialogInterface.OnClickListener dissmisslistener) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton("确定", listener);
        if (cancelable) {
            builder.setNegativeButton("取消", dissmisslistener);
        }
        builder.setCancelable(cancelable);
        //builder.setIcon(R.mipmap.quickdevelop_ic_launcher);
        dialog = builder.create();
        dialog.show();
    }
}
